//
// DotNetNuke - http://www.dotnetnuke.com
// Copyright (c) 2002-2010
// by Perpetual Motion Interactive Systems Inc. ( http://www.perpetualmotion.ca )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//

using System;
using System.Collections;
using System.Data;
using System.IO;
using System.Text.RegularExpressions;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Security;
using DotNetNuke.Security.Permissions;
using DotNetNuke.Services.FileSystem;
using DotNetNuke.Services.Localization;
using DotNetNuke.UI.Utilities;
using DotNetNuke.UI.WebControls;
using ICSharpCode.SharpZipLib.Zip;

using DNNTreeNode = DotNetNuke.UI.WebControls.TreeNode;
using DNNTreeNodeCollection = DotNetNuke.UI.WebControls.TreeNodeCollection;
using Microsoft.VisualBasic;
namespace DotNetNuke.Modules.Admin.FileManager
{
	partial class FileManager : DotNetNuke.Entities.Modules.PortalModuleBase
	{
		private enum eImageType
		{
			Folder = 0,
			SecureFolder = 1,
			DatabaseFolder = 2,
			Page = 3
		}
		private bool _DisplayingMessage;
		private string m_strParentFolderName;
		private string imageDirectory = "~/images/FileManager/Icons/";
		private string _ErrorMessage = "<TABLE><TR><TD height=100% class=NormalRed>{0}</TD></TR><TR valign=bottom><TD align=center><INPUT id=btnClearError onclick=clearErrorMessage(); type=button value=OK></TD></TR></TABLE>";
		protected bool IsAdminRole
		{
			get { return PortalSecurity.IsInRole(PortalSettings.AdministratorRoleName); }
		}
		protected bool HasPermission(string permissionKey)
		{
			bool _HasPermision = Null.NullBoolean;
			string strSourcePath = UnMaskPath(DestPath).Replace(RootFolderPath, "").Replace("\\", "/");
			FolderController objFolders = new FolderController();
			FolderInfo objFolder = objFolders.GetFolder(FolderPortalID, strSourcePath, false);
			if (objFolder != null)
			{
				_HasPermision = IsEditable && FolderPermissionController.HasFolderPermission(objFolder.FolderPermissions, permissionKey);
			}
			return _HasPermision;
		}
		public int FolderPortalID
		{
			get
			{
				if (IsHostMenu)
				{
					return Null.NullInteger;
				}
				else
				{
					return PortalId;
				}
			}
		}
		public string RootFolderName
		{
			get
			{
				if (ViewState["RootFolderName"] != null)
				{
					return ViewState["RootFolderName"].ToString();
				}
				else
				{
					return "";
				}
			}
			set { ViewState["RootFolderName"] = value; }
		}
		public string RootFolderPath
		{
			get
			{
				string _CurRootFolder;
				if (IsHostMenu)
				{
					_CurRootFolder = Common.Globals.HostMapPath;
				}
				else
				{
					_CurRootFolder = PortalSettings.HomeDirectoryMapPath;
				}
				return _CurRootFolder;
			}
		}
		public string Sort
		{
			get { return ViewState["strSort"].ToString(); }
			set { ViewState.Add("strSort", value); }
		}
		public string LastSort
		{
			get { return ViewState["strLastSort"].ToString(); }
			set { ViewState.Add("strLastSort", value); }
		}
		public string FilterFiles
		{
			get { return ViewState["strFilterFiles"].ToString(); }
			set { ViewState.Add("strFilterFiles", value); }
		}
		public string LastPath
		{
			get { return UnMaskPath(ClientAPI.GetClientVariable(Page, "LastPath")); }
			set
			{
				value = MaskPath(value);
				ClientAPI.RegisterClientVariable(Page, "LastPath", value, true);
			}
		}
		public string DestPath
		{
			get { return ClientAPI.GetClientVariable(Page, "DestPath"); }
			set { ClientAPI.RegisterClientVariable(Page, "DestPath", value, true); }
		}
		public string SourcePath
		{
			get { return ClientAPI.GetClientVariable(Page, "SourcePath"); }
			set { ClientAPI.RegisterClientVariable(Page, "SourcePath", value, true); }
		}
		public string MoveFiles
		{
			get { return ClientAPI.GetClientVariable(Page, "MoveFiles"); }
			set { ClientAPI.RegisterClientVariable(Page, "MoveFiles", value, true); }
		}
		public bool IsRefresh
		{
			get { return Convert.ToBoolean(ClientAPI.GetClientVariable(Page, "IsRefresh")); }
			set { ClientAPI.RegisterClientVariable(Page, "IsRefresh", Convert.ToString(Convert.ToInt32(value)), true); }
		}
		public bool DisabledButtons
		{
			get { return Convert.ToBoolean(ClientAPI.GetClientVariable(Page, "DisabledButtons")); }
			set { ClientAPI.RegisterClientVariable(Page, "DisabledButtons", Convert.ToString(Convert.ToInt32(value)), true); }
		}
		public string MoveStatus
		{
			get { return ClientAPI.GetClientVariable(Page, "MoveStatus"); }
			set { ClientAPI.RegisterClientVariable(Page, "MoveStatus", value, true); }
		}
		public string LastFolderPath
		{
			get
			{
				if (ViewState["LastFolderPath"] != null)
				{
					return ViewState["LastFolderPath"].ToString();
				}
				else
				{
					return "";
				}
			}
			set { ViewState["LastFolderPath"] = value; }
		}
		public int PageSize
		{
			get { return Convert.ToInt32(selPageSize.SelectedValue); }
		}
		public int PageIndex
		{
			get
			{
				if (ViewState["PageIndex"] != null)
				{
					return Convert.ToInt32(ViewState["PageIndex"]);
				}
				else
					return 0;
			}
			set
			{
				if (value >= 0 && value < dgFileList.PageCount)
					ViewState["PageIndex"] = value;
			}
		}
		private void AddFileToTable(DataTable tblFiles, DotNetNuke.Services.FileSystem.FileInfo objFile)
		{
			DataRow dRow;
			dRow = tblFiles.NewRow();
			dRow["FileType"] = "File";
			dRow["FileId"] = objFile.FileId;
			dRow["FileName"] = objFile.FileName;
			dRow["FileSize"] = objFile.Size.ToString("##,##0");
			dRow["IntFileSize"] = objFile.Size;
			if (!String.IsNullOrEmpty(objFile.Extension) || objFile.Extension != null)
			{
				dRow["Extension"] = objFile.Extension;
			}
			else
			{
				dRow["Extension"] = "none";
			}
			dRow["StorageLocation"] = objFile.StorageLocation;
			string strSourcePath;
			System.IO.FileInfo fsFile;
			switch (objFile.StorageLocation)
			{
				case (int)FolderController.StorageLocationTypes.InsecureFileSystem:
					strSourcePath = UnMaskPath(DestPath);
					fsFile = new System.IO.FileInfo(strSourcePath + objFile.FileName);
					dRow["DateModified"] = fsFile.LastWriteTime;
					dRow["Archive"] = fsFile.Attributes & FileAttributes.Archive;
					dRow["ReadOnly"] = fsFile.Attributes & FileAttributes.ReadOnly;
					dRow["Hidden"] = fsFile.Attributes & FileAttributes.Hidden;
					dRow["System"] = fsFile.Attributes & FileAttributes.System;
					dRow["AttributeString"] = GetAttributeString(fsFile.Attributes);
					break;
				case (int)FolderController.StorageLocationTypes.SecureFileSystem:
					strSourcePath = UnMaskPath(DestPath);
					fsFile = new System.IO.FileInfo(strSourcePath + objFile.FileName + Common.Globals.glbProtectedExtension);
					dRow["DateModified"] = fsFile.LastWriteTime;
					dRow["Archive"] = fsFile.Attributes & FileAttributes.Archive;
					dRow["ReadOnly"] = fsFile.Attributes & FileAttributes.ReadOnly;
					dRow["Hidden"] = fsFile.Attributes & FileAttributes.Hidden;
					dRow["System"] = fsFile.Attributes & FileAttributes.System;
					dRow["AttributeString"] = GetAttributeString(fsFile.Attributes);
					break;
				case (int)FolderController.StorageLocationTypes.DatabaseSecure:
					dRow["Archive"] = false;
					dRow["ReadOnly"] = false;
					dRow["Hidden"] = false;
					dRow["System"] = false;
					dRow["AttributeString"] = "";
					break;
			}
			tblFiles.Rows.Add(dRow);
		}
		private DNNTreeNode AddNode(string strName, string strKey, eImageType eImage, DNNTreeNodeCollection objNodes)
		{
			DNNTreeNode objNode;
			objNode = new DNNTreeNode(strName);
			objNode.Key = strKey;
			objNode.ToolTip = strName;
			objNode.ImageIndex = (int)eImage;
			objNode.CssClass = "FileManagerTreeNode";
			objNodes.Add(objNode);
			if (objNode.Key == DestPath)
			{
				objNode.Selected = true;
				objNode.MakeNodeVisible();
			}
			return objNode;
		}
		private DNNTreeNode AddNode(FolderInfo folder, DNNTreeNodeCollection objNodes)
		{
			DNNTreeNode objNode;
			string strName = folder.FolderName;
			string strKey = MaskPath(RootFolderPath + folder.FolderPath);
			ArrayList subFolders = FileSystemUtils.GetFoldersByParentFolder(FolderPortalID, folder.FolderPath);
			eImageType image = eImageType.Folder;
			switch (folder.StorageLocation)
			{
				case (int)FolderController.StorageLocationTypes.InsecureFileSystem:
					image = eImageType.Folder;
					break;
				case (int)FolderController.StorageLocationTypes.SecureFileSystem:
					image = eImageType.SecureFolder;
					break;
				case (int)FolderController.StorageLocationTypes.DatabaseSecure:
					image = eImageType.DatabaseFolder;
					break;
			}
			objNode = AddNode(strName, strKey, image, objNodes);
			objNode.HasNodes = subFolders.Count > 0;
			return objNode;
		}
		private void BindFileList()
		{
			string strCurPage;
			LastPath = FileSystemUtils.RemoveTrailingSlash(UnMaskPath(DestPath));
			dgFileList.PageSize = PageSize;
			dgFileList.CurrentPageIndex = PageIndex;
			GetFilesByFolder(FileSystemUtils.StripFolderPath(DestPath).Replace("\\", "/"));
			if (dgFileList.PageCount > 1)
			{
				tblMessagePager.Visible = true;
				strCurPage = Localization.GetString("Pages");
				lblCurPage.Text = string.Format(strCurPage, (dgFileList.CurrentPageIndex + 1), (dgFileList.PageCount));
				lnkMoveFirst.Text = "<img border=0 Alt='" + Localization.GetString("First") + "' src='" + ResolveUrl("~/images/FileManager/movefirst.gif") + "'>";
				lnkMovePrevious.Text = "<img border=0 Alt='" + Localization.GetString("Previous") + "' src='" + ResolveUrl("~/images/FileManager/moveprevious.gif") + "'>";
				lnkMoveNext.Text = "<img border=0 Alt='" + Localization.GetString("Next") + "' src='" + ResolveUrl("~/images/FileManager/movenext.gif") + "'>";
				lnkMoveLast.Text = "<img border=0 Alt='" + Localization.GetString("Last") + "' src='" + ResolveUrl("~/images/FileManager/movelast.gif") + "'>";
			}
			else
			{
				tblMessagePager.Visible = false;
			}
			lblCurFolder.Text = Regex.Replace(DestPath, "^0\\\\", RootFolderName + "\\");
			MoveFiles = "";
			UpdateSpaceUsed();
		}
		private void BindStorageLocationTypes()
		{
			ddlStorageLocation.Items.Add(new ListItem(Localization.GetString("InsecureFileSystem", this.LocalResourceFile), "0"));
			ddlStorageLocation.Items.Add(new ListItem(Localization.GetString("SecureFileSystem", this.LocalResourceFile), "1"));
			ddlStorageLocation.Items.Add(new ListItem(Localization.GetString("SecureDatabase", this.LocalResourceFile), "2"));
		}
		private void BindFolderTree()
		{
			DNNTreeNode objNode;
			DNNTree.TreeNodes.Clear();
			objNode = AddNode(RootFolderName, MaskPath(RootFolderPath), eImageType.Folder, DNNTree.TreeNodes);
			ArrayList arrFolders = FileSystemUtils.GetFolders(FolderPortalID);
			objNode.HasNodes = arrFolders.Count > 1;
			if (this.DNNTree.PopulateNodesFromClient == false || this.DNNTree.IsDownLevel)
			{
				PopulateTree(objNode.TreeNodes, RootFolderPath);
			}
			if (DNNTree.SelectedTreeNodes.Count == 0)
				objNode.Selected = true;
		}
		private string GetCheckAllString()
		{
			int intCount = dgFileList.Items.Count;
			CheckBox chkFile;
			int i;
			string strResult;
			strResult = "setMoveFiles('');" + Environment.NewLine;
			for (i = 0; i <= intCount - 1; i++)
			{
				chkFile = (CheckBox)dgFileList.Items[i].FindControl("chkFile");
				if ((chkFile) != null)
				{
					strResult = strResult + "var chk1 = dnn.dom.getById('" + chkFile.ClientID + "');";
					strResult = strResult + "chk1.checked = blValue;" + Environment.NewLine;
					strResult = strResult + "if (!chk1.onclick) {chk1.parentElement.onclick();}else{chk1.onclick();}" + Environment.NewLine;
				}
			}
			strResult = "function CheckAllFiles(blValue) {" + strResult + "}" + Environment.NewLine;
			strResult = "<script language=javascript>" + strResult + "</script>";
			return strResult;
		}
		private void GeneratePermissionsGrid()
		{
			string folderPath = FileSystemUtils.StripFolderPath(DestPath).Replace("\\", "/");
			dgPermissions.FolderPath = folderPath;
			FolderInfo objFolderInfo = new FolderInfo();
			FolderController objFolderController = new FolderController();
			objFolderInfo = objFolderController.GetFolder(FolderPortalID, folderPath, false);
			if (objFolderInfo != null)
			{
				ddlStorageLocation.SelectedValue =Convert.ToString(objFolderInfo.StorageLocation);
			}
		}
		private string GetAttributeString(System.IO.FileAttributes attributes)
		{
			string strResult = "";
			if ((attributes & FileAttributes.Archive) == FileAttributes.Archive)
			{
				strResult += "A";
			}
			if ((attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
			{
				strResult += "R";
			}
			if ((attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
			{
				strResult += "H";
			}
			if ((attributes & FileAttributes.System) == FileAttributes.System)
			{
				strResult += "S";
			}
			return strResult;
		}
		private void GetFilesByFolder(string strFolderName)
		{
			DataTable tblFiles = GetFileTable();
			FolderInfo objFolder = FileSystemUtils.GetFolder(FolderPortalID, strFolderName);
			if (objFolder != null)
			{
				ArrayList arrFiles = FileSystemUtils.GetFilesByFolder(FolderPortalID, objFolder.FolderID);
				foreach (DotNetNuke.Services.FileSystem.FileInfo objFile in arrFiles)
				{
					AddFileToTable(tblFiles, objFile);
				}
			}
			DataView dv = new DataView();
			dv.Table = tblFiles;
			dv.Sort = Sort;
			if (!String.IsNullOrEmpty(FilterFiles))
			{
				dv.RowFilter = "FileName like '%" + this.FilterFiles + "%'";
			}
			dgFileList.DataSource = dv;
			dgFileList.DataBind();
		}
		private DataTable GetFileTable()
		{
			DataTable tblFiles = new DataTable("Files");
			DataColumn myColumns = new DataColumn();
			myColumns.DataType = System.Type.GetType("System.String");
			myColumns.ColumnName = "FileType";
			tblFiles.Columns.Add(myColumns);
			myColumns = new DataColumn();
			myColumns.DataType = System.Type.GetType("System.Int32");
			myColumns.ColumnName = "FileId";
			tblFiles.Columns.Add(myColumns);
			myColumns = new DataColumn();
			myColumns.DataType = System.Type.GetType("System.String");
			myColumns.ColumnName = "FileName";
			tblFiles.Columns.Add(myColumns);
			myColumns = new DataColumn();
			myColumns.DataType = System.Type.GetType("System.String");
			myColumns.ColumnName = "FileSize";
			tblFiles.Columns.Add(myColumns);
			myColumns = new DataColumn();
			myColumns.DataType = System.Type.GetType("System.Int32");
			myColumns.ColumnName = "IntFileSize";
			tblFiles.Columns.Add(myColumns);
			myColumns = new DataColumn();
			myColumns.DataType = System.Type.GetType("System.Int32");
			myColumns.ColumnName = "StorageLocation";
			tblFiles.Columns.Add(myColumns);
			myColumns = new DataColumn();
			myColumns.DataType = System.Type.GetType("System.DateTime");
			myColumns.ColumnName = "DateModified";
			tblFiles.Columns.Add(myColumns);
			myColumns = new DataColumn();
			myColumns.DataType = System.Type.GetType("System.Boolean");
			myColumns.ColumnName = "ReadOnly";
			tblFiles.Columns.Add(myColumns);
			myColumns = new DataColumn();
			myColumns.DataType = System.Type.GetType("System.Boolean");
			myColumns.ColumnName = "Hidden";
			tblFiles.Columns.Add(myColumns);
			myColumns = new DataColumn();
			myColumns.DataType = System.Type.GetType("System.Boolean");
			myColumns.ColumnName = "System";
			tblFiles.Columns.Add(myColumns);
			myColumns = new DataColumn();
			myColumns.DataType = System.Type.GetType("System.Boolean");
			myColumns.ColumnName = "Archive";
			tblFiles.Columns.Add(myColumns);
			myColumns = new DataColumn();
			myColumns.DataType = System.Type.GetType("System.String");
			myColumns.ColumnName = "AttributeString";
			tblFiles.Columns.Add(myColumns);
			myColumns = new DataColumn();
			myColumns.DataType = System.Type.GetType("System.String");
			myColumns.ColumnName = "Extension";
			tblFiles.Columns.Add(myColumns);
			return tblFiles;
		}
		private long GetZipFileExtractSize(string strFileName)
		{
			ZipEntry objZipEntry;
			ZipInputStream objZipInputStream;
			try
			{
				objZipInputStream = new ZipInputStream(File.OpenRead(strFileName));
			}
			catch (Exception ex)
			{
				ShowErrorMessage(MaskString(ex.Message));
				return -1;
			}
			objZipEntry = objZipInputStream.GetNextEntry();
			long iTemp = 0;
			while (objZipEntry != null)
			{
				iTemp = iTemp + objZipEntry.Size;
				objZipEntry = objZipInputStream.GetNextEntry();
			}
			objZipInputStream.Close();
			return iTemp;
		}
		private void InitializeTree()
		{
			DNNTree.SystemImagesPath = ResolveUrl("~/images/");
			DNNTree.ImageList.Add(ResolveUrl("~/images/folder.gif"));
			DNNTree.ImageList.Add(ResolveUrl("~/images/icon_securityroles_16px.gif"));
			DNNTree.ImageList.Add(ResolveUrl("~/images/icon_sql_16px.gif"));
			DNNTree.ImageList.Add(ResolveUrl("~/images/file.gif"));
			DNNTree.IndentWidth = 10;
			DNNTree.CollapsedNodeImage = ResolveUrl("~/images/max.gif");
			DNNTree.ExpandedNodeImage = ResolveUrl("~/images/min.gif");
			DNNTree.PopulateNodesFromClient = true;
			DNNTree.JSFunction = "nodeSelected();";
		}
		private void ManageToolbarButton(HtmlGenericControl wrapperControl, System.Web.UI.WebControls.Image imageControl, string js, string imageRootName, bool enableButton)
		{
			if (enableButton)
			{
				wrapperControl.Attributes.Add("style", "cursor: pointer");
				wrapperControl.Attributes.Add("onclick", js);
				imageControl.ImageUrl = "~/images/FileManager/ToolBar" + imageRootName + "Enabled.gif";
			}
			else
			{
				wrapperControl.Attributes.Remove("style");
				wrapperControl.Attributes.Remove("onclick");
				imageControl.ImageUrl = "~/images/FileManager/ToolBar" + imageRootName + "Disabled.gif";
			}
		}
		private void ManageSecurity()
		{
			ManageToolbarButton(addFolder, lnkAddFolderIMG, "return canAddFolder();", "AddFolder", HasPermission("ADD"));
			ManageToolbarButton(deleteFolder, lnkDelFolderIMG, "return deleteFolder();", "DelFolder", HasPermission("DELETE"));
			ManageToolbarButton(syncFolder, lnkSyncFolderIMG, "__doPostBack(m_sUCPrefixName + 'lnkSyncFolder', '');", "Synchronize", HasPermission("MANAGE"));
			chkRecursive.Enabled = HasPermission("MANAGE");
			ManageToolbarButton(refresh, lnkRefreshIMG, "__doPostBack(m_sUCPrefixName + 'lnkRefresh', '');", "Refresh", true);
			ManageToolbarButton(copy, lnkCopy, "copyCheckedFiles();", "Copy", HasPermission("COPY"));
			ManageToolbarButton(move, lnkMove, "moveFiles();", "Move", HasPermission("COPY"));
			ManageToolbarButton(upload, lnkUploadIMG, "__doPostBack(m_sUCPrefixName + 'lnkUpload', '');", "Upload", HasPermission("ADD"));
			ManageToolbarButton(delete, lnkDelete, "deleteCheckedFiles();", "Delete", HasPermission("DELETE"));
			ManageToolbarButton(filter, lnkFilterIMG, "__doPostBack(m_sUCPrefixName + 'lnkFilter', '');", "Filter", true);
			lnkCopy.Enabled = IsEditable;
			lnkMove.Enabled = IsEditable;
			lnkUpload.Enabled = IsEditable;
			lnkDelete.Enabled = IsEditable;
		}
		private string MaskPath(string strOrigPath)
		{
			return strOrigPath.Replace(FileSystemUtils.RemoveTrailingSlash(RootFolderPath), "0").Replace("/", "\\");
		}
		private string MaskString(string strSource)
		{
			return FileManagerFunctions.CReplace(strSource, FileSystemUtils.RemoveTrailingSlash(RootFolderPath), Localization.GetString("PortalRoot", this.LocalResourceFile), 1);
		}
		private void PopulateTree(DNNTreeNodeCollection objNodes, string strPath)
		{
			string folderPath = strPath.Replace(RootFolderPath, "").Replace("\\", "/");
			ArrayList folders = FileSystemUtils.GetFoldersByParentFolder(FolderPortalID, folderPath);
			DNNTreeNode objNode;
			foreach (FolderInfo folder in folders)
			{
				if (FolderPermissionController.CanViewFolder(folder))
				{
					objNode = AddNode(folder, objNodes);
					if (this.DNNTree.PopulateNodesFromClient == false)
					{
						PopulateTree(objNode.TreeNodes, folder.FolderPath);
					}
				}
			}
		}
		private void SetFolder(DNNTreeNode node)
		{
			dgFileList.EditItemIndex = -1;
			if (DNNTree.IsDownLevel)
			{
				DestPath = node.Key;
				LastPath = node.Key;
			}
			ManageSecurity();
			BindFileList();
			GeneratePermissionsGrid();
		}
		private void SetEditMode()
		{
			if (dgFileList.EditItemIndex > -1)
			{
				int intCount = dgFileList.Items.Count;
				CheckBox chkFile2;
				CheckBox chkFile;
				ImageButton lnkDeleteFile;
				ImageButton lnkEditFile;
				int i;
				for (i = 0; i <= intCount - 1; i++)
				{
					if (i != dgFileList.EditItemIndex)
					{
						chkFile2 = (CheckBox)dgFileList.Items[i].FindControl("chkFile2");
						chkFile = (CheckBox)dgFileList.Items[i].FindControl("chkFile");
						lnkDeleteFile = (ImageButton)dgFileList.Items[i].FindControl("lnkDeleteFile");
						lnkEditFile = (ImageButton)dgFileList.Items[i].FindControl("lnkEditFile");
						if ((chkFile2) != null)
							chkFile2.Enabled = false;
						if ((chkFile) != null)
							chkFile.Enabled = false;
						if ((lnkDeleteFile) != null)
						{
							lnkDeleteFile.Enabled = false;
							lnkDeleteFile.ImageUrl = "~/images/FileManager/DNNExplorer_trash_disabled.gif";
							lnkDeleteFile.AlternateText = "";
						}
						if ((lnkEditFile) != null)
						{
							lnkEditFile.Enabled = false;
							lnkEditFile.ImageUrl = "~/images/FileManager/DNNExplorer_Edit_disabled.gif";
							lnkEditFile.AlternateText = "";
						}
						chkFile2 = null;
						chkFile = null;
						lnkDeleteFile = null;
						lnkEditFile = null;
					}
				}
				this.DisabledButtons = true;
			}
			else
			{
			}
			dgFileList.Columns[0].HeaderStyle.Width = System.Web.UI.WebControls.Unit.Percentage(5);
			dgFileList.Columns[1].HeaderStyle.Width = System.Web.UI.WebControls.Unit.Percentage(25);
			dgFileList.Columns[2].HeaderStyle.Width = System.Web.UI.WebControls.Unit.Percentage(25);
			dgFileList.Columns[3].HeaderStyle.Width = System.Web.UI.WebControls.Unit.Percentage(7);
			dgFileList.Columns[4].HeaderStyle.Width = System.Web.UI.WebControls.Unit.Percentage(15);
		}
		private void ShowErrorMessage(string strMessage)
		{
			strMessage = strMessage.Replace( "\\", "\\\\");
			strMessage = strMessage.Replace( "'", "\\'");
			strMessage = strMessage.Replace( Environment.NewLine, "\\n");
			strMessage = string.Format(_ErrorMessage, strMessage);
			_DisplayingMessage = true;
			ClientAPI.RegisterClientVariable(this.Page, "ErrorMessage", strMessage, true);
		}
		private void Synchronize()
		{
			if (IsHostMenu)
			{
				FileSystemUtils.Synchronize(Null.NullInteger, Null.NullInteger, Common.Globals.HostMapPath, false);
			}
			else
			{
				FileSystemUtils.Synchronize(PortalId, PortalSettings.AdministratorRoleId, PortalSettings.HomeDirectoryMapPath, PortalSettings.HideFoldersEnabled);
			}
		}
		private string UnMaskPath(string strOrigPath)
		{
			strOrigPath = FileSystemUtils.AddTrailingSlash(RootFolderPath) + FileSystemUtils.StripFolderPath(strOrigPath);
			return strOrigPath.Replace("/", "\\");
		}
		private void UpdateSpaceUsed()
		{
			string strDestFolder = FileSystemUtils.AddTrailingSlash(UnMaskPath(DestPath));
			PortalController objPortalController = new PortalController();
			string strUsed;
			string strQuota;
			if (PortalSettings.HostSpace == 0)
			{
				strQuota = Localization.GetString("UnlimitedSpace", this.LocalResourceFile);
			}
			else
			{
				strQuota = PortalSettings.HostSpace.ToString() + "MB";
			}
			if (IsHostMenu)
			{
				lblFileSpace.Text = "&nbsp;";
			}
			else
			{
				long spaceUsed = objPortalController.GetPortalSpaceUsedBytes(FolderPortalID);
				if (spaceUsed < 1024)
				{
					strUsed = spaceUsed.ToString("0.00") + "B";
				}
				else if (spaceUsed < (1024 * 1024))
				{
					strUsed = (spaceUsed / 1024).ToString("0.00") + "KB";
				}
				else
				{
					strUsed = (spaceUsed / (1024 * 1024)).ToString("0.00") + "MB";
				}
				lblFileSpace.Text = string.Format(Localization.GetString("SpaceUsed", this.LocalResourceFile), strUsed, strQuota);
			}
		}
		protected void DeleteFiles(string strFiles)
		{
			string[] arFiles = strFiles.Split(';');
			int i;
			if (arFiles.Length == 0)
			{
				return;
			}
			string strSourcePath;
			string strErrorMessage = "";
			string strCurError;
			strSourcePath = FileSystemUtils.AddTrailingSlash(LastPath);
			for (i = 0; i <= arFiles.Length - 1; i++)
			{
				if (!String.IsNullOrEmpty(arFiles[i]))
				{
					strCurError = FileSystemUtils.DeleteFile(strSourcePath + arFiles[i], PortalSettings, false);
					if (!String.IsNullOrEmpty(strCurError))
					{
						strErrorMessage = strErrorMessage + Localization.GetString("ErrorDeletingFile", this.LocalResourceFile) + FileSystemUtils.AddTrailingSlash(UnMaskPath(DestPath)) + arFiles[i] + "<BR>&nbsp;&nbsp;&nbsp;" + strCurError + "<BR>";
					}
				}
			}
			if (!String.IsNullOrEmpty(strErrorMessage))
			{
				strErrorMessage = MaskString(strErrorMessage);
				ShowErrorMessage(strErrorMessage);
			}
			BindFileList();
		}
		protected override void Render(System.Web.UI.HtmlTextWriter output)
		{
			Page.ClientScript.RegisterForEventValidation(lnkAddFolder.UniqueID);
			Page.ClientScript.RegisterForEventValidation(lnkDeleteFolder.UniqueID);
			Page.ClientScript.RegisterForEventValidation(lnkDeleteAllCheckedFiles.UniqueID);
			Page.ClientScript.RegisterForEventValidation(lnkRefresh.UniqueID);
			Page.ClientScript.RegisterForEventValidation(lnkSelectFolder.UniqueID);
			Page.ClientScript.RegisterForEventValidation(lnkSyncFolder.UniqueID);
			Page.ClientScript.RegisterForEventValidation(lnkFilter.UniqueID);
			Page.ClientScript.RegisterForEventValidation(lnkCopy.UniqueID);
			Page.ClientScript.RegisterForEventValidation(lnkUpload.UniqueID);
			Page.ClientScript.RegisterForEventValidation(lnkMove.UniqueID);
			Page.ClientScript.RegisterForEventValidation(lnkMoveFirst.UniqueID);
			Page.ClientScript.RegisterForEventValidation(lnkMoveLast.UniqueID);
			Page.ClientScript.RegisterForEventValidation(lnkMoveNext.UniqueID);
			Page.ClientScript.RegisterForEventValidation(lnkMovePrevious.UniqueID);
			Page.ClientScript.RegisterForEventValidation(lnkMoveFiles.UniqueID);
			string strTemp = GetCheckAllString();
			pnlScripts2.Controls.Add(new LiteralControl(strTemp));
			if (dgFileList.Items.Count <= 10 && dgFileList.PageCount == 1)
			{
				dgFileList.PagerStyle.Visible = false;
			}
			base.Render(output);
		}
		public string CheckDestFolderAccess(long intSize)
		{
			if (Request.IsAuthenticated)
			{
				string strDestFolder = FileSystemUtils.AddTrailingSlash(UnMaskPath(DestPath));
				PortalController objPortalController = new PortalController();
				if (objPortalController.HasSpaceAvailable(FolderPortalID, intSize) || (PortalSettings.ActiveTab.ParentId == PortalSettings.SuperTabId))
				{
					return "";
				}
				else
				{
					return Localization.GetString("NotEnoughSpace", this.LocalResourceFile);
				}
			}
			else
			{
				return Localization.GetString("PleaseLogin", this.LocalResourceFile);
			}
		}
		public string GetImageUrl(string type)
		{
			string url = "";
			try
			{
				if (type == "folder")
				{
					url = imageDirectory + "ClosedFolder.gif";
				}
				else
				{
					if (!String.IsNullOrEmpty(type) && File.Exists(Server.MapPath(imageDirectory + type + ".gif")))
					{
						url = imageDirectory + type + ".gif";
					}
					else
					{
						url = imageDirectory + "File.gif";
					}
				}
			}
			catch (Exception exc)
			{
				Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
			}
			return url;
		}

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            cmdUpdate.Click += new EventHandler(cmdUpdate_Click);
            dgFileList.ItemDataBound += new DataGridItemEventHandler(dgFileList_ItemDataBound);
            dgFileList.SortCommand += new DataGridSortCommandEventHandler(dgFileList_SortCommand);
            DNNTree.NodeClick += new DnnTree.DNNTreeNodeClickHandler(DNNTree_NodeClick);
            DNNTree.PopulateOnDemand += new DnnTree.DNNTreeEventHandler(DNNTree_PopulateOnDemand);
            lnkAddFolder.Command += new CommandEventHandler(lnkAddFolder_Command);
            lnkDeleteFolder.Command += new CommandEventHandler(lnkDeleteFolder_Command);
            lnkFilter.Command += new CommandEventHandler(lnkFilter_Command);
            lnkDeleteAllCheckedFiles.Command += new CommandEventHandler(lnkDeleteAllCheckedFiles_Command);
            lnkMoveFiles.Command += new CommandEventHandler(lnkMoveFiles_Command);
            lnkMoveFirst.Command += new CommandEventHandler(lnkMoveFirst_Command);
            lnkMoveLast.Command += new CommandEventHandler(lnkMoveLast_Command);
            lnkMoveNext.Command += new CommandEventHandler(lnkMoveNext_Command);
            lnkMovePrevious.Command += new CommandEventHandler(lnkMovePrevious_Command);
            lnkRefresh.Command += new CommandEventHandler(lnkRefresh_Command);
            lnkSelectFolder.Command += new CommandEventHandler(lnkSelectFolder_Command);
            lnkSyncFolder.Command += new CommandEventHandler(lnkSyncFolder_Command);
            lnkSyncFolders.Click += new ImageClickEventHandler(lnkSyncFolders_Click);
            lnkUpload.Command += new CommandEventHandler(lnkUpload_Command);
            selPageSize.SelectedIndexChanged += new EventHandler(selPageSize_SelectedIndexChanged);
        }

		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);

			try
			{
				ClientAPI.RegisterClientReference(this.Page, ClientAPI.ClientNamespaceReferences.dnn);
				DNNClientAPI.AddBodyOnloadEventHandler(this.Page, "initFileManager();");
				ClientAPI.RegisterClientVariable(this.Page, "UCPrefixID", DNNTree.ClientID.Replace(DNNTree.ID, ""), true);
				ClientAPI.RegisterClientVariable(this.Page, "UCPrefixName", DNNTree.UniqueID.Replace(DNNTree.ID, ""), true);
				if (DNNTree.IsDownLevel)
				{
					this.DisabledButtons = true;
				}
				else
				{
					this.DisabledButtons = false;
				}
				if (IsHostMenu)
				{
					RootFolderName = Localization.GetString("HostRoot", this.LocalResourceFile);
					pnlSecurity.Visible = false;
				}
				else
				{
					RootFolderName = Localization.GetString("PortalRoot", this.LocalResourceFile);
					pnlSecurity.Visible = HasPermission("WRITE");
				}
				if (Page.IsPostBack == false)
				{
					Common.Utilities.DataCache.ClearFolderCache(FolderPortalID);
					Localization.LocalizeDataGrid(ref dgFileList, this.LocalResourceFile);
					InitializeTree();
					BindFolderTree();
					IsRefresh = true;
					PageIndex = 0;
					Sort = "FileType ASC, FileName ASC";
					LastSort = "FileType ASC, FileName ASC";
					MoveStatus = "";
					FilterFiles = "";
					DestPath = "0\\";
					BindFileList();
					BindStorageLocationTypes();
					ManageSecurity();
				}
				else
				{
					FilterFiles = txtFilter.Text;
				}
				if (LastFolderPath != DestPath)
				{
					PageIndex = 0;
					GeneratePermissionsGrid();
				}
				LastFolderPath = DestPath;
			}
			catch (Exception exc)
			{
				Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
			}
		}
		private void cmdUpdate_Click(System.Object sender, System.EventArgs e)
		{
			string strFolderPath = FileSystemUtils.StripFolderPath(this.LastFolderPath).Replace("\\", "/");
			FolderController objFolderController = new FolderController();
			FolderInfo objFolderInfo = objFolderController.GetFolder(FolderPortalID, strFolderPath, false);
			if (objFolderInfo == null)
			{
				Synchronize();
				objFolderInfo = objFolderController.GetFolder(FolderPortalID, strFolderPath, true);
			}
			objFolderInfo.FolderPermissions.Clear();
			objFolderInfo.FolderPermissions.AddRange(dgPermissions.Permissions);
			try
			{
				FolderPermissionController.SaveFolderPermissions(objFolderInfo);
				DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("PermissionsUpdated", this.LocalResourceFile), DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.GreenSuccess);
			}
			catch (Exception ex)
			{
				Services.Exceptions.Exceptions.LogException(ex);
				DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("PermissionsError", this.LocalResourceFile), DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError);
			}
			GeneratePermissionsGrid();
		}
		private void dgFileList_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
		{
			ImageButton lnkEditFile;
			CheckBox chkFile;
			ImageButton lnkDeleteFile;
			System.Web.UI.WebControls.Image lnkUnzip;
			ImageButton lnkOkRename;
			bool blEnabled = true;
			if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.EditItem || e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.SelectedItem)
			{
				chkFile = (CheckBox)e.Item.FindControl("chkFile");
				if (chkFile != null)
				{
					string sDefCssClass = dgFileList.ItemStyle.CssClass;
					if (e.Item.ItemType == ListItemType.AlternatingItem)
						sDefCssClass = dgFileList.AlternatingItemStyle.CssClass;
					chkFile.Attributes.Add("onclick", "addFileToMoveList('" + ClientAPI.GetSafeJSString(chkFile.Attributes["filename"]) + "', this, '" + dgFileList.SelectedItemStyle.CssClass + "', '" + sDefCssClass + "');");
				}
				lnkEditFile = (System.Web.UI.WebControls.ImageButton)e.Item.FindControl("lnkEditFile");
				if (lnkEditFile != null)
				{
					lnkEditFile.CommandName = e.Item.ItemIndex.ToString();
				}
				lnkUnzip = (System.Web.UI.WebControls.Image)e.Item.FindControl("lnkUnzip");
				if (lnkUnzip != null)
				{
					if (lnkUnzip.Attributes["extension"] != "zip")
					{
						lnkUnzip.Visible = false;
					}
					else
					{
						if (e.Item.ItemType == ListItemType.EditItem)
						{
							lnkUnzip.Visible = false;
						}
						else
						{
							lnkUnzip.Attributes.Add("onclick", "return unzipFile('" + ClientAPI.GetSafeJSString(lnkUnzip.Attributes["filename"]) + "');");
						}
					}
				}
				lnkDeleteFile = (System.Web.UI.WebControls.ImageButton)e.Item.FindControl("lnkDeleteFile");
				if (lnkDeleteFile != null)
				{
					if (dgFileList.EditItemIndex == -1)
					{
						ClientAPI.AddButtonConfirm(lnkDeleteFile, string.Format(Localization.GetString("EnsureDeleteFile", this.LocalResourceFile), lnkDeleteFile.CommandName));
					}
				}
				lnkOkRename = (System.Web.UI.WebControls.ImageButton)e.Item.FindControl("lnkOkRename");
				if (lnkOkRename != null)
				{
					lnkOkRename.CommandName = e.Item.ItemIndex.ToString();
				}
			}
		}
		protected void dgFileList_SortCommand(object source, System.Web.UI.WebControls.DataGridSortCommandEventArgs e)
		{
			BindFolderTree();
			this.IsRefresh = true;
			LastSort = Sort;
			if (Sort.Replace(" ASC", "").Replace(" DESC", "") == e.SortExpression)
			{
				if (Sort.Contains("ASC"))
				{
					Sort = Sort.Replace("ASC", "DESC");
				}
				else
				{
					Sort = Sort.Replace("DESC", "ASC");
				}
			}
			else
			{
				Sort = e.SortExpression + " ASC";
			}
			MoveStatus = "";
			FilterFiles = "";
			BindFileList();
		}
		private void DNNTree_NodeClick(object source, DotNetNuke.UI.WebControls.DNNTreeNodeClickEventArgs e)
		{
			SetFolder(e.Node);
		}
		private void DNNTree_PopulateOnDemand(object source, UI.WebControls.DNNTreeEventArgs e)
		{
			DestPath = e.Node.Key;
			PopulateTree(e.Node.TreeNodes, UnMaskPath(e.Node.Key.Replace("\\\\", "\\")));
			GeneratePermissionsGrid();
		}
		private void lnkAddFolder_Command(object sender, System.Web.UI.WebControls.CommandEventArgs e)
		{
			if (String.IsNullOrEmpty(this.txtNewFolder.Text))
			{
				return;
			}
			string strSourcePath;
			strSourcePath = UnMaskPath(DestPath);
			try
			{
                if (DNNTree.TreeNodes[0].DNNNodes.Count == 0)
                {
                    PopulateTree(DNNTree.TreeNodes[0].TreeNodes, RootFolderPath);
                }

			    Collection colNodes = DNNTree.SelectedTreeNodes;
				if (colNodes.Count > 0)
				{
					DNNTreeNode parentNode = (DNNTreeNode)colNodes[1];
					string filterFolderName;
					filterFolderName = txtNewFolder.Text.Replace(".", "_");
					FileSystemUtils.AddFolder(PortalSettings, strSourcePath, filterFolderName, int.Parse(ddlStorageLocation.SelectedValue));
					DestPath = MaskPath(FileSystemUtils.AddTrailingSlash(strSourcePath) + filterFolderName + "\\");
                    LastFolderPath = DestPath;
					parentNode.Selected = false;
					eImageType image = eImageType.Folder;
					switch (int.Parse(ddlStorageLocation.SelectedValue))
					{
						case (int)FolderController.StorageLocationTypes.InsecureFileSystem:
							image = eImageType.Folder;
							break;
						case (int)FolderController.StorageLocationTypes.SecureFileSystem:
							image = eImageType.SecureFolder;
							break;
						case (int)FolderController.StorageLocationTypes.DatabaseSecure:
							image = eImageType.DatabaseFolder;
							break;
					}
					DNNTreeNode objNode = AddNode(filterFolderName, parentNode.Key.Replace("\\\\", "\\") + filterFolderName + "\\", image, parentNode.TreeNodes);
					objNode.HasNodes = false;
					objNode.MakeNodeVisible();
					objNode.Selected = true;
					SetFolder(objNode);
				}
			}
			catch (Exception ex)
			{
				string strErrorMessage = MaskString(ex.Message);
				ShowErrorMessage(strErrorMessage);
			}
			txtNewFolder.Text = "";
		}
		private void lnkDeleteFolder_Command(object sender, System.Web.UI.WebControls.CommandEventArgs e)
		{
			string strSourcePath;
			LiteralControl ctrlError = new LiteralControl();
			if (DestPath == DNNTree.TreeNodes[0].Key)
			{
				ShowErrorMessage(Localization.GetString("NotAllowedToDeleteRootFolder", this.LocalResourceFile));
				BindFileList();
				return;
			}
			else
			{
				strSourcePath = UnMaskPath(DestPath);
			}
			System.IO.DirectoryInfo dinfo = new System.IO.DirectoryInfo(strSourcePath);
			if (dinfo.Exists == false)
			{
				ShowErrorMessage(Localization.GetString("FolderAlreadyRemoved", this.LocalResourceFile));
				BindFileList();
				return;
			}
			if ((System.IO.Directory.GetDirectories(strSourcePath).Length > 0) || (dgFileList.Items.Count > 0))
			{
				ShowErrorMessage(Localization.GetString("PleaseRemoveFilesBeforeDeleting", this.LocalResourceFile));
				BindFileList();
				return;
			}
			try
			{
				string folderName = FileSystemUtils.StripFolderPath(DestPath);
				FileSystemUtils.DeleteFolder(FolderPortalID, dinfo, folderName);
				int intEnd;
				if (DestPath.EndsWith("\\"))
					DestPath = DestPath.Substring(0, DestPath.Length - 1);
				intEnd = DestPath.LastIndexOf("\\");
				DestPath = DestPath.Substring(0, intEnd);
				Collection colNodes = DNNTree.SelectedTreeNodes;
				if (colNodes.Count > 0)
				{
					DNNTreeNode objNode = (DNNTreeNode)colNodes[1];
					objNode.Selected = false;
					objNode.Parent.Selected = true;
					objNode.Parent.DNNNodes.Remove(objNode);
				}
				BindFileList();
				GeneratePermissionsGrid();
			}
			catch (Exception ex)
			{
				ShowErrorMessage(Localization.GetString("ErrorDeletingFolder", this.LocalResourceFile) + ex.Message);
			}
		}
		protected void lnkDLFile_Command(object sender, System.Web.UI.WebControls.CommandEventArgs e)
		{
			FileSystemUtils.DownloadFile(PortalSettings, Convert.ToInt32(e.CommandArgument), false, true);
			BindFolderTree();
		}
		protected void lnkEditFile_Command(object sender, System.Web.UI.WebControls.CommandEventArgs e)
		{
			dgFileList.EditItemIndex = Convert.ToInt32(e.CommandName);
			BindFileList();
			SetEditMode();
		}
		protected void lnkCancelRename_Command(object sender, System.Web.UI.WebControls.CommandEventArgs e)
		{
			dgFileList.EditItemIndex = -1;
			BindFileList();
			SetEditMode();
		}
		private void lnkDeleteAllCheckedFiles_Command(object sender, System.Web.UI.WebControls.CommandEventArgs e)
		{
			if (!String.IsNullOrEmpty(this.MoveFiles))
			{
				DeleteFiles(MoveFiles);
			}
		}
		protected void lnkDeleteFile_Command(object sender, System.Web.UI.WebControls.CommandEventArgs e)
		{
			DeleteFiles(e.CommandName);
		}
		private void lnkFilter_Command(object sender, System.Web.UI.WebControls.CommandEventArgs e)
		{
			this.dgFileList.CurrentPageIndex = 0;
			BindFileList();
		}
		private void lnkMoveFiles_Command(object sender, System.Web.UI.WebControls.CommandEventArgs e)
		{
			string[] arFiles;
			arFiles = MoveFiles.Split(';');
			int i;
			string strSourceFile;
			string strDestFile;
			string strErrorMessages = "";
			string strCurErrorMessage = "";
			string strSourcePath;
			string strDestPath;
			strDestPath = FileSystemUtils.AddTrailingSlash(UnMaskPath(DestPath));
			strSourcePath = FileSystemUtils.AddTrailingSlash(UnMaskPath(SourcePath));
			if (!HasPermission("ADD"))
			{
				strErrorMessages = Localization.GetString("NoWritePermission", this.LocalResourceFile);
			}
			if (String.IsNullOrEmpty(strErrorMessages))
			{
				for (i = 0; i <= arFiles.Length - 1; i++)
				{
					if (!String.IsNullOrEmpty(arFiles[i]))
					{
						strSourceFile = strSourcePath + arFiles[i];
						strDestFile = strDestPath + arFiles[i];
						strCurErrorMessage = "";
						switch (MoveStatus)
						{
							case "copy":
								strCurErrorMessage = FileSystemUtils.CopyFile(strSourceFile, strDestFile, PortalSettings);
								break;
							case "move":
								strCurErrorMessage = FileSystemUtils.MoveFile(strSourceFile, strDestFile, PortalSettings);
								break;
							case "unzip":
								strCurErrorMessage = FileSystemUtils.UnzipFile(strSourceFile, strDestPath, PortalSettings);
								BindFolderTree();
								break;
						}
						if (!String.IsNullOrEmpty(strCurErrorMessage))
						{
							if (MoveStatus == "copy")
							{
								strErrorMessages = strErrorMessages + Localization.GetString("ErrorCopyingFile", this.LocalResourceFile) + FileSystemUtils.AddTrailingSlash(UnMaskPath(SourcePath)) + arFiles[i] + "&nbsp;&nbsp; to " + FileSystemUtils.AddTrailingSlash(UnMaskPath(DestPath)) + "<BR>&nbsp;&nbsp;&nbsp;" + strCurErrorMessage + "<BR>";
							}
							else
							{
								strErrorMessages = strErrorMessages + Localization.GetString("ErrorMovingFile", this.LocalResourceFile) + FileSystemUtils.AddTrailingSlash(UnMaskPath(SourcePath)) + arFiles[i] + "&nbsp;&nbsp; to " + FileSystemUtils.AddTrailingSlash(UnMaskPath(DestPath)) + "<BR>&nbsp;&nbsp;&nbsp;" + strCurErrorMessage + "<BR>";
							}
						}
					}
				}
			}
			if (String.IsNullOrEmpty(strErrorMessages))
			{
				LastPath = FileSystemUtils.RemoveTrailingSlash(DestPath);
			}
			else
			{
				strErrorMessages = MaskString(strErrorMessages);
				strErrorMessages = MaskString(strErrorMessages);
				ShowErrorMessage(strErrorMessages);
			}
			ManageSecurity();
			BindFileList();
			MoveStatus = "";
			SourcePath = "";
		}
		protected void lnkMoveFirst_Command(object sender, System.Web.UI.WebControls.CommandEventArgs e)
		{
			PageIndex = 0;
			BindFileList();
		}
		protected void lnkMoveLast_Command(object sender, System.Web.UI.WebControls.CommandEventArgs e)
		{
			this.PageIndex = this.dgFileList.PageCount - 1;
			BindFileList();
		}
		protected void lnkMoveNext_Command(object sender, System.Web.UI.WebControls.CommandEventArgs e)
		{
			PageIndex += 1;
			if (PageIndex > dgFileList.PageCount - 1)
			{
				PageIndex = dgFileList.PageCount - 1;
			}
			BindFileList();
		}
		protected void lnkMovePrevious_Command(object sender, System.Web.UI.WebControls.CommandEventArgs e)
		{
			PageIndex -= 1;
			if (PageIndex < 0)
			{
				PageIndex = 0;
			}
			BindFileList();
		}
		protected void lnkOkRename_Command(object sender, System.Web.UI.WebControls.CommandEventArgs e)
		{
			string strSourcePath;
			int intItemID = Convert.ToInt32(e.CommandName);
			strSourcePath = FileSystemUtils.AddTrailingSlash(UnMaskPath(DestPath));
			string strFileName = e.CommandArgument.ToString();
			TextBox txtEdit;
			txtEdit = (TextBox)dgFileList.Items[intItemID].FindControl("txtEditFileName");
			string strSourceFile;
			strSourceFile = strSourcePath + e.CommandArgument.ToString();
			string strDestFile = strSourcePath + txtEdit.Text;
			string strReturn = "";
			string strError = "";
			if (strSourceFile != strDestFile)
			{
				strError = FileSystemUtils.MoveFile(strSourceFile, strDestFile, PortalSettings);
				if (!String.IsNullOrEmpty(strError))
				{
					strError = Localization.GetString("Rename.Error", this.LocalResourceFile) + strError;
				}
				else
				{
					strSourceFile = strDestFile;
				}
			}
			if (String.IsNullOrEmpty(strError))
			{
				CheckBox chkReadOnly = (CheckBox)dgFileList.Items[intItemID].FindControl("chkReadOnly");
				CheckBox chkHidden = (CheckBox)dgFileList.Items[intItemID].FindControl("chkHidden");
				CheckBox chkSystem = (CheckBox)dgFileList.Items[intItemID].FindControl("chkSystem");
				CheckBox chkArchive = (CheckBox)dgFileList.Items[intItemID].FindControl("chkArchive");
				if ((chkReadOnly.Attributes["original"] != chkReadOnly.Checked.ToString()) || (chkHidden.Attributes["original"] != chkHidden.Checked.ToString()) || (chkSystem.Attributes["original"] != chkSystem.Checked.ToString()) || (chkArchive.Attributes["original"] != chkArchive.Checked.ToString()))
				{
					int iAttr = 0;
					if (chkReadOnly.Checked)
						iAttr += (int)FileAttributes.ReadOnly;
					if (chkHidden.Checked)
						iAttr += (int)FileAttributes.Hidden;
					if (chkSystem.Checked)
						iAttr += (int)FileAttributes.System;
					if (chkArchive.Checked)
						iAttr += (int)FileAttributes.Archive;
					try
					{
						FileSystemUtils.SetFileAttributes(strSourceFile, iAttr);
					}
					catch (Exception ex)
					{
						strError = ex.Message;
					}
					if (!String.IsNullOrEmpty(strError))
					{
						strError = Localization.GetString("SetAttrubute.Error", this.LocalResourceFile) + strError;
					}
				}
			}
			if (!String.IsNullOrEmpty(strError))
			{
				ShowErrorMessage(MaskString(strError));
			}
			dgFileList.EditItemIndex = -1;
			BindFileList();
			SetEditMode();
		}
		private void lnkRefresh_Command(object sender, System.Web.UI.WebControls.CommandEventArgs e)
		{
			BindFolderTree();
			this.IsRefresh = true;
			Sort = "FileType ASC, FileName ASC";
			LastSort = "FileType ASC, FileName ASC";
			MoveStatus = "";
			FilterFiles = "";
			BindFileList();
		}
		private void lnkSelectFolder_Command(object sender, System.Web.UI.WebControls.CommandEventArgs e)
		{
			string strSourcePath = DestPath;
			string strFriendlyPath = Regex.Replace(strSourcePath, "^0\\\\", "Portal Root\\");
			dgFileList.CurrentPageIndex = 0;
			UI.Utilities.ClientAPI.AddButtonConfirm(lnkDeleteFolder, string.Format(Localization.GetString("EnsureDeleteFolder", this.LocalResourceFile), strFriendlyPath));
			strSourcePath = UnMaskPath(strSourcePath.Replace("\\\\", "\\"));
			LastPath = strSourcePath;
			GetFilesByFolder(FileSystemUtils.AddTrailingSlash(strSourcePath));
		}
		private void lnkSyncFolder_Command(object sender, System.Web.UI.WebControls.CommandEventArgs e)
		{
			string syncFolderPath = UnMaskPath(DestPath);
			bool isRecursive = chkRecursive.Checked;
			string relPath = syncFolderPath.Replace(RootFolderPath, "").Replace("\\", "/");
			FileSystemUtils.SynchronizeFolder(FolderPortalID, syncFolderPath, relPath, isRecursive, PortalSettings.HideFoldersEnabled);
			BindFolderTree();
			BindFileList();
		}
		protected void lnkSyncFolders_Click(object sender, System.Web.UI.ImageClickEventArgs e)
		{
			if (IsHostMenu)
			{
				FileSystemUtils.SynchronizeFolder(Null.NullInteger, Common.Globals.HostMapPath, "", true, false, true, false);
			}
			else
			{
				FileSystemUtils.SynchronizeFolder(PortalId, PortalSettings.HomeDirectoryMapPath, "", true, false, true, false);
			}
			BindFolderTree();
			BindFileList();
		}
		private void lnkUpload_Command(object sender, System.Web.UI.WebControls.CommandEventArgs e)
		{
			string strDestPath = Regex.Replace(DestPath, "^0\\\\", "");
			string WebUploadParam = "ftype=" + UploadType.File.ToString();
			string returnTab = "rtab=" + TabId;
			string destUrl = EditUrl("dest", Common.Globals.QueryStringEncode(strDestPath), "Edit", WebUploadParam, returnTab);
			Response.Redirect(destUrl);
		}
		private void selPageSize_SelectedIndexChanged(System.Object sender, System.EventArgs e)
		{
			PageIndex = 0;
			BindFileList();
		}
	}
}
